<template>
  <div>
    <div style="height: 50px;">
      <p style="font-weight: normal;font-size: 24px;">个人资料</p>
    </div>
    <el-row style="background-color: white;padding: 15px;">
      <el-col :span="6">
        <div style="padding: 25px">
          <div class="card img-hover">
            <label class="img-mask">
              <i class="el-icon-picture" style="padding: 10px"></i> 点击上传头像
              <input type="file" accept="image/*" hidden @change="change">
            </label>
            <!--上传照片-->
            <img :src="img.url" class="avator-img">
          </div>
        </div>
        <div>
          <div style="float: left;width: 100%;padding: 15px 0px 15px 30px;">
            <span style="color: #303133;">{{form.name}}</span>
            <span style="color: #606266;font-size: 15px;margin-left: 10px">{{currentRole.name}}</span>
          </div>
          <div class="clearfix"></div>
          <div style="padding: 15px 0px 0px 30px;color: #909399">最近登录时间：</div>
          <div style="padding: 15px 0px 0px 30px;color: #909399">{{form.visited}}</div>
        </div>
      </el-col>
      <el-col :span="18" style="padding: 15px">
        <el-form :model="form" label-position="top" :rules="rules" ref="form" label-width="100px" class="user-form">
          <el-form-item label="昵称" prop="nick" class="my-form-item">
            <el-input v-model="form.nick"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pass" class="my-form-item">
            <el-input v-model="form.pass" type="password" placeholder="密码（无需修改请留空）"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email" class="my-form-item">
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone" class="my-form-item">
            <el-input v-model="form.phone"></el-input>
          </el-form-item>
          <el-form-item label="生日" prop="birthday" class="my-form-item">
            <el-date-picker type="date" placeholder="选择生日" v-model="form.birthday"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-form-item>
          <el-form-item label="性别" prop="gender" class="my-form-item">
            <el-radio-group v-model="form.gender">
              <el-radio label="1">男</el-radio>
              <el-radio label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="6">
        &nbsp;
      </el-col>
      <el-col :span="18">
        <div style="padding: 15px">
          <el-button plain round type="info" @click="back" icon="el-icon-back">返回</el-button>
          <el-button plain type="primary" @click="submitForm('form')" icon="el-icon-circle-check">保存</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {User, Role, FileMapping} from '../../utils/resource'
  import util from '../../utils/util'
  import {showSaveResponse, validFieldExists, validateForm, SessionStorageUtil} from '../../utils/element-helper'
  import {mapState, mapActions} from 'vuex'
  import * as qiniu from 'qiniu-js'

  let maxsize = 1024 * 1024   // 最大1MB
  let token

  export default {
    name: 'userProfile',
    components: {},
    data() {
      return {
        initForm: {},// for edit
        loading: false,
        currentRole: {},
        form: {
          gender: "1",
        },
        img: {
          complete: false,
          total: {
            percent: 0
          },
          size: 0,
          url: ''
        },
        rules: {
          nick: [
            {required: true, message: '账号不能为空', trigger: 'blur'},
          ],
          email: [
            {required: true, message: '邮箱地址不能为空', trigger: 'blur'},
            {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur']},
            {
              validator: (rule, value, callback) => {
                this.validateExists(rule, value, callback)
              }, trigger: 'blur'
            }
          ],
          phone: [
            {required: true, message: '手机号码不能为空', trigger: 'blur'},
            {pattern: /^1[34578]\d{9}$/, message: '目前只支持中国大陆的手机号码'},
            {
              validator: (rule, value, callback) => {
                this.validateExists(rule, value, callback)
              }, trigger: 'blur'
            }
          ],
          pass: [
            {min: 5, max: 25, message: '密码长度在 5 到 25 位之间', trigger: 'blur'},
          ],
        },
      }
    },
    created() {
      this.loadUser()
      this.loadCurrentRole()
    },
    computed: {

    },
    methods: {
      loadUser() {
        let user = SessionStorageUtil.getItem("user")
        user.gender = String(user.gender)
        if(user.avatar === ''|| user.avatar == null){
          user.avatar = require('../../assets/big_timg.png')
        }
        this.img.url = user.avatar
        this.form = user
        this.initForm = user
      },
      async loadCurrentRole() {
        let res = await Role.getCurrentRole()
        this.currentRole = res.data.data
      },
      submitForm(formName) {
        return validateForm(this, formName, () => {
          //不修改密码需要将密码清空
          let tempForm = Object.assign({}, this.form)
          if (tempForm.pass === '') {
            delete tempForm['pass']
          }
          showSaveResponse(this, () => User.modify(tempForm), (res) => {
              SessionStorageUtil.setItem("user", tempForm)
              this.$router.back()
            }
          )
        })
      },
      validateExists(rule, value, callback) {
        validFieldExists(rule, value, callback, this.initForm[rule.field] != value, (rule, value) => User.exists(rule, value))
      },
      //上传文件改变
      async change(e) {
        if (token) return this.upload(e.target)
        let res = await FileMapping.uploadToken()
        token = res.data.data
        this.upload(e.target)
      },
      back() {
        this.$router.back()
      },
      upload(target) {
        let vue = this
        if (target.files.length == 0) return
        let file = target.files[0]
        if (file.size > maxsize) {
          return this.$message.error('文件大小超过限制, 请上传小于' + util.fileSize(maxsize) + '的图片')
        }
        Object.assign(this.img, {
          complete: false,
          total: {
            percent: 0,
            loaded: 0,
            size: 0
          },
          size: file.size,
          name: file.name,
          type: file.type,
          url: ''
        })
        let reader = new FileReader() // 如果为图片文件, 读取DataURL显示图片
        reader.readAsDataURL(file)
        reader.onload = (e) => this.img.url = e.target.result
        let key = util.shorten() + file.name.substr(file.name.lastIndexOf('.'))
        let that = this
        qiniu.upload(file, key, token).subscribe({ // 开始上传
          next: (res) => that.img.total = res.total,
          error: (err) => console.log('error', err),
          complete(res) {
            that.img.complete = true
            let item = {
              parent: 10,//头像文件夹编号
              name: that.img.name,
              mime: that.img.type,
              size: that.img.size,
              hash: that.img.hash,
              key: res.key,
              folder: 0,
            }
            FileMapping.save(item, "post").then(response => {
              Object.assign(that.img, response.data.data)
              let avatar = response.data.data.url
              User.avatar({avatar}).then(res => {
                if (res.data.success) {
                  that.$message.success('头像已更新')
                  let user = SessionStorageUtil.getItem("user")
                  SessionStorageUtil.setItem("user", Object.assign(user, {avatar}))
                  vue.$emit('refreshSessionStorge')
                }
              })
            })
          }
        })
        target.value = ''
      },

    },
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .user-form {
    width: 90%;
  }

  .my-form-item {
    max-width: 600px;
  }

</style>
<style>
  .my-form-input {
    max-width: 330px;
  }

  .img-mask:hover {
    background: rgba(0, 0, 0, .6);
    cursor: pointer;
  }

  .img-mask:hover,
  .img-hover:hover .img-mask {
    opacity: 1;
    visibility: visible;
  }

  .avator-img {
    max-width: 100%;
    height: auto;
    border-radius: .25rem .25rem 0 0;
    display: block;
  }

  .img-mask {
    color: #fff !important;
    border-radius: .25rem .25rem 0 0;
    background: rgba(0, 0, 0, .3);
    width: 100%;
    height: 15%;
    min-height: 35px;
    margin: 0;
    opacity: 0;
    visibility: hidden;
    text-align: center;
    position: absolute;
    transition: all .3s ease-in-out;
  }

  .card {
    position: relative;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-direction: column;
    flex-direction: column;
    min-width: 0;
    word-wrap: break-word;
    background-color: #fff;
    background-clip: border-box;
    border: 1px solid rgba(0, 0, 0, .125);
    border-radius: .25rem;
  }
</style>
